﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Claims;
using System.Linq;
using System.Reflection;
using System.Text;
using Hsi.Utility.Identity;
using IdentityAtRest.Utility.Identity;

namespace IdentityAtRest.Utility.Identity.ExpressionEval
{
    public class ClaimNameResolutionService : IVariableResolutionService
    {
        private readonly IList<IClaim> _claims;
        private static readonly Dictionary<string, string> _claimAliases;

        static ClaimNameResolutionService()
        {
            _claimAliases = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase);
            MapAliasesFor(typeof (ClaimTypes));
            MapAliasesFor(typeof (CustomClaimTypes));
        }

        private static void MapAliasesFor(Type claimType)
        {
            PropertyInfo[] props = claimType.GetProperties();
            foreach (PropertyInfo prop in props)
            {
                if (prop.PropertyType == typeof(string))
                {
                    _claimAliases[prop.Name] = (string)prop.GetValue(null, null);
                }
            }
        }

        public ClaimNameResolutionService (IList<IClaim> claims)
        {
            _claims = claims;
        }

        public object ResolveVariableValue(string variableName)
        {
            if (_claimAliases.ContainsKey(variableName))
            {
                return _claims.GetClaimValue<object>(_claimAliases[variableName]);
            }
            return null;
        }
    }
}